import sceneConf from '../../confs/scene-conf'

export default class GameOverPage {
  constructor(callbacks) {
    this.callbacks = callbacks
  }

  init(options){
    // 3D环境绘制2D结束界面
    console.log("init game-over-page")
    this.initGameoverCanvas(options)
  }

  /**
   * 将scence 和 camera 从 gamePage 传入
   */
  initGameoverCanvas(options) {
    // 创建canvas 并将其贴到某个Three.js 对象上

    // 计算屏幕宽高比
    const aspect = window.innerHeight / window.innerWidth
    this.region = [
      (window.innerWidth - 200) / 2,
      (window.innerWidth - 200) / 2 + 200,
      (window.innerHeight - 100) / 2,
      (window.innerHeight - 100) / 2 + 100
    ]
    this.camera = options.camera
    // this.scene = options.scene

    // canvas 和最后映射长宽比保持一致
    this.canvas = document.createElement('canvas')
    this.canvas.width = window.innerWidth
    this.canvas.height = window.innerHeight

    // 通过texture(纹理)得到material，再将material贴到geometry 
    this.texture = new THREE.Texture(this.canvas)
    this.material = new THREE.MeshBasicMaterial({ map: this.texture, transparent: true, side: THREE.DoubleSide });
    // 这里是修改为camera 后的参数
    this.geometry = new THREE.PlaneGeometry(sceneConf.frustumSize * 2, aspect * sceneConf.frustumSize * 2)
    // 之前scene 旋转三角形参数
    // this.geometry = new THREE.PlaneGeometry(window.innerWidth, window.innerHeight)

    this.obj = new THREE.Mesh(this.geometry, this.material)
    this.obj.position.z = 20
    // 绕y轴旋转180度, camera不需要旋转
    // this.obj.rotation.y = Math.PI
    // gameover 图形绘制，canvas只是html上容器
    this.context = this.canvas.getContext('2d')
    // 填充颜色
    this.context.fillStyle = '#333'
    // 绘制矩形
    this.context.fillRect((window.innerWidth - 200) / 2, (window.innerHeight - 100) / 2, 200, 100)
    this.context.fillStyle = '#eee'
    this.context.font = '20px Georgia'
    this.context.fillText('Game Over', (window.innerWidth - 200) / 2 + 50, (window.innerHeight - 100) / 2 + 55)
    // 纹理改变了
    this.texture.needsUpdate = true
    this.obj.visible = false
    this.camera.add(this.obj)
    // this.scene.instance.add(this.obj)
  }

  show() {
    this.obj.visible = true
    this.bindTouchEvent()
  }

  hide() {
    this.obj.visible = false
    this.removeTouchEvent()
  }

  bindTouchEvent() {
    canvas.addEventListener('touchend', this.onTouchEnd)
  }

  removeTouchEvent() {
    canvas.removeEventListener('touchend', this.onTouchEnd)
  }
  
  onTouchEnd = (e) => {
    const pageX = e.changedTouches[0].pageX
    const pageY = e.changedTouches[0].pageY
    if (pageX > this.region[0] && pageX < this.region[1] && pageY > this.region[2] && pageY < this.region[3]) { // restart
      this.callbacks.gameRestart()
    }
  }
}